import WxRequest from './request'
import { clearStorage, getStorage } from './storage'
import { toast, modal } from './extendApi'

const instance = new WxRequest({
  baseUrl: 'https://gmall-prod.atguigu.cn/mall-api',
  timeout: 15000
})

//请求拦截器
instance.interceptors.request = (config) => {
  const token = getStorage('token')
  if (token) {
    config.header['token'] = token
  }
  return config
}

//响应拦截器
instance.interceptors.response = (response) => {
  const { isSuccess, data } = response
  if (!isSuccess) {
    wx.showToast({
      title: '数据请求超时',
      duration: 1500,
      icon: 'error'
    })
    return response
  }
  switch (data.code) {
    case 200:
      return data
    case 208:
      const solve208 = async () => {
        const res = await modal({
          content: '鉴权失败，请重新登录',
          showCancel: false
        })
        if (res) {
          clearStorage()
          wx.navigateTo({
            url: '/pages/login/login'
          })
        }
        return Promise.reject(response)
      }
      solve208()
    default:
      toast({
        title: '操作出现异常',
        duration: 1500
      })
  }
  return data
}

export default instance
